package me.majiajie.pagerbottomtabstrip.internal;

import ohos.agp.colors.RgbColor;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.render.Canvas;
import ohos.agp.render.Texture;
import ohos.app.Context;
import ohos.global.resource.NotExistException;
import ohos.global.resource.ResourceManager;
import ohos.global.resource.WrongTypeException;
import ohos.media.image.PixelMap;
import ohos.media.image.common.AlphaType;
import ohos.media.image.common.PixelFormat;
import ohos.media.image.common.Size;

import java.io.IOException;

/**
 * 工具类
 */
public class Utils {

    /**
     * PixelMap 染色
     *
     * @param oldPixelMap 染色对象
     * @param color       颜色
     * @return 染色后的资源
     */
    public static PixelMap tinting(PixelMap oldPixelMap, int color) {
        PixelMap.InitializationOptions initializationOptions = new PixelMap.InitializationOptions();
        initializationOptions.pixelFormat = PixelFormat.ARGB_8888;
        initializationOptions.alphaType = AlphaType.PREMUL;
        initializationOptions.size = new Size(oldPixelMap.getImageInfo().size.width, oldPixelMap.getImageInfo().size.height);
        PixelMap newPixelMap = PixelMap.create(oldPixelMap, initializationOptions);

        Canvas canvas = new Canvas(new Texture(newPixelMap));
        canvas.drawColor(color, Canvas.PorterDuffMode.SRC_IN);
        return newPixelMap;
    }

    /**
     * ShapeElement 染色
     *
     * @param drawable 染色对象
     * @param color    颜色
     * @return 染色后的资源
     */
    public static ShapeElement tinting(ShapeElement drawable, int color) {
        drawable.setRgbColor(new RgbColor(color));
        return drawable;
    }

    public static PixelMap newDrawable(PixelMap drawable) {
        // 利用ConstantState节省内存资源，暂无实现
        return drawable;
    }

    /**
     * 获取colorPrimary的颜色
     *
     * @param context 上下文
     * @return 0xAARRGGBB
     */
    public static int getColorPrimary(Context context) {
        // 获取colorPrimary的颜色，暂无实现
        return 0xFF009688;
    }

    /**
     * vp转换为px
     *
     * @param context 上下文
     * @param vp      vp
     * @return px
     */
    public static int vpToPx(Context context, float vp) {
        return (int) (context.getResourceManager().getDeviceCapability().screenDensity / 160 * vp);
    }

    /**
     * 获取xml属性值
     *
     * @param context 上下文
     * @param id      属性值对应的id
     * @return 属性值
     */
    public static float getDimen(Context context, int id) {
        float result = 0;
        if (context == null) {
            return result;
        }
        ResourceManager manager = context.getResourceManager();
        if (manager == null) {
            return result;
        }
        try {
            result = manager.getElement(id).getFloat();
        } catch (IOException | NotExistException | WrongTypeException exception) {
            result = 0;
        }
        return result;
    }

}
